package cn.codergege.demo.dsl

open class Tag(val name: String) : Node {
    var children = ArrayList<Tag>()
    var properties = HashMap<String, String>()

    operator fun String.invoke(value: String) {
        this@Tag.properties[this] = value
    }

    operator fun String.invoke(block: Tag.() -> Unit) {
        this@Tag.children.add(Tag(this).apply(block))
    }

    override fun render(): String {
        return StringBuilder()
            .append("<")
            .append(name)
            .let { sb ->
                if (this.properties.isEmpty())
                else {
                    this.properties.forEach {
                        sb.append(" ")
                            .append(it.key)
                            .append("=\"")
                            .append(it.value)
                            .append("\"")
                    }
                }
                sb
            }.append(">")
            .let { sb ->
                this.children.map {
//                    Node::render
                    it.render()
                }.map {
//                    StringBuilder::append
                    sb.append(it)
                }
                sb
            }.append("</$name>")
            .toString()
    }

}